﻿using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.GraphicsSystem;
using Autodesk.AutoCAD.Windows;
using generic_class;
using data_adapter;

namespace pallete_main
{
    public partial class TreeViewControl : UserControl
    {
        private MySqlConnection conn;
        private Hashtable htNode;
        private Hashtable htDeviceNode;
        private Hashtable htDeviceId;
        //private DataAdapter adapter;

        public TreeViewControl()
        {
            InitializeComponent();
        }


        public void init()
        {
            htNode = new Hashtable();
            htDeviceNode = new Hashtable();
            htDeviceId = new Hashtable();
            //conn = new MySqlConnection("Database=smartdb;Data Source=localhost;User Id=root;Password=zwxx");
            //conn = new MySQLConnection(connString.AsString);
            //conn.Open();
            // command = new MySqlCommand("set names gb2312", conn);
            //command.ExecuteNonQuery();

            
        }

        public void createTree(string schema, TreeView tView)
        {
            string sql = "select v.volume_id,v.name,d.dwg_id,d.name,d.type from "+schema+".volume v left join "+schema
                         +".dwg d on v.volume_id=d.volume_id order by v.volume_id,d.dwg_id";
            DataAdapter adapter = new DataAdapter();

            System.Data.DataTable dataTable = adapter.GetDataTable(sql);

            uint id;
            uint parentId;
            String parentName = null;
            String nodeName = null;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                parentId = (uint)dataTable.Rows[i][0];
                parentName = (string)dataTable.Rows[i][1];
                
                if (!htNode.ContainsKey(parentId))
                {
                    TreeNode parentNode = new TreeNode(parentName);
                    htNode.Add(parentId, parentNode);
                    tView.Nodes.Add(parentNode);
                }
                if (dataTable.Rows[i][2] != DBNull.Value)
                {
                    id = (uint)dataTable.Rows[i][2];
                    nodeName = (String)dataTable.Rows[i][3];
                    TreeNode node = new TreeNode(nodeName);
                    htNode.Add(node,id);
                    ((TreeNode)htNode[parentId]).Nodes.Add(node);
                }
            }

            adapter.CloseConnection();

        }

        private void TreeViewControl_Load(object sender, EventArgs e)
        {
            init();
            //创建卷册树
            createTree("dctss_project9", treeView2);

            //创建设备树
            //createDeviceTree(6, 0, treeView1);
            treeView1.createDeviceTree("dctss_project9");
            treeView1.changeShowType(_device_show_type.BAY);

            comboBox1.Items.Add("按间隔");
            comboBox1.Items.Add("按电压");
            comboBox1.Items.Add("按屏柜");
            comboBox1.Items.Add("按设备");
            comboBox1.SelectedIndex = 0;
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                treeView1.ContextMenuStrip = menu_device;
            }

        }

        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            TreeNode node = e.Node;
            foreach (TreeNode item in node.Nodes)
            {
                item.Checked = e.Node.Checked;
            }

        }

        private void comboBox1_SelectedChange(object sender, EventArgs e) 
        {
            ComboBox comboBox = (ComboBox)sender;
            int selectedIndex = comboBox.SelectedIndex;
            treeView1.changeShowType((_device_show_type)selectedIndex);
        }

        private void Show_Dialog(_paper_type type)
        {
            int[] device = treeView1.getSelectedDeviceId();

            if (null != device)
            {
                export dialog = new export(device,type);
                dialog.ShowDialog();
            }
            else
            {
                MessageBox.Show("没有选择出图的设备");
            }
        }

        private void goose_router_Click(object sender, EventArgs e)
        {
            Show_Dialog(0);
        }

        private void goose_device_Click(object sender, EventArgs e)
        {
            Show_Dialog(0);
        }

        private void sv_cell_Click(object sender, EventArgs e)
        {
            Show_Dialog(0);
        }

        private void sv_device_Click(object sender, EventArgs e)
        {
            Show_Dialog(0);
        }

        private ArrayList CreateData()
        {
            ArrayList lst = new ArrayList();

            _router router = new _router();
            router.name = "测试路由器";
            router.list_port = new ArrayList();

            for (int i = 0; i < 10; i++)
            {
                _port port = new _port();
                if ((i % 2) == 0)
                    port.name ="设备" + i.ToString();
                else
                    port.name = null;
                port.port_name = i.ToString();
                router.list_port.Add(port);
            }
            lst.Add(router);
            return lst;
        }

        private void zu_wang_goose_Click(object sender, EventArgs e)
        {
          //  Show_Dialog();

            module_zuwang module = new module_zuwang();
            module.DrawZuWang(CreateData());
        }

        private void zu_wang_sv_Click(object sender, EventArgs e)
        {
            Show_Dialog(0);

        }

        private void zu_wang_process_Click(object sender, EventArgs e)
        {
            Show_Dialog(0);

        }

        private void zu_wang_time_Click(object sender, EventArgs e)
        {
            Show_Dialog(0);

        }

        private void zu_wang_station_Click(object sender, EventArgs e)
        {
            Show_Dialog(0);

        }

        private void gllxt_paper_Click(object sender, EventArgs e)
        {
            Show_Dialog(_paper_type.TYPE_PAPER);

        }

        private void gllxt_table_Click(object sender, EventArgs e)
        {
            Show_Dialog(_paper_type.TYPE_EXCEL);

        }

        private void gllxt_both_Click(object sender, EventArgs e)
        {
            Show_Dialog(_paper_type.TYPE_BOTH);

        }

        private void xu_duanzi_paper_Click(object sender, EventArgs e)
        {
            Show_Dialog(_paper_type.TYPE_PAPER);

        }

        private void xu_duanzi_table_Click(object sender, EventArgs e)
        {
            Show_Dialog(_paper_type.TYPE_EXCEL);

        }

        private void xu_duanzi_both_Click(object sender, EventArgs e)
        {
            Show_Dialog(_paper_type.TYPE_BOTH);

        }

        private void treeView2_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
                return;

            switch(e.Node.Level)
            {
                //目录
                case 0:
                    treeView2.ContextMenuStrip = menu_juance;
                    break;
                //文件名
                case 1:
                    treeView2.ContextMenuStrip = menu_paper;
                    break;

            }

        }

        private void TreeViewControl_Layout(object sender, System.Windows.Forms.LayoutEventArgs e)
        {
            tableLayoutPanel2.Size = new Size(this.ClientSize.Width,this.ClientSize.Height);
        }

        private void treeView2_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void tableLayoutPanel2_Paint(object sender, PaintEventArgs e)
        {

        }


        //拷贝dwg文件元素到指定的位置
        private ObjectId CopyDWG(string sourcename,Point3d position)
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            ObjectId editId;
                 
            if(!File.Exists(sourcename))
            {
                MessageBox.Show("文件不存在");
                return ObjectId.Null;
            }

            try
            {
                Database db = new Database(false, true);
                db.ReadDwgFile(sourcename, FileShare.Read, true, "");
                db.CloseInput(true);

                DocumentLock docLock = doc.LockDocument();
                Database destDb = doc.Database;

                using (Transaction trans = doc.TransactionManager.StartTransaction())
                {
                    string blockname = SymbolUtilityServices.GetBlockNameFromInsertPathName(sourcename);
                    ObjectId id = destDb.Insert(blockname, db, false);
                    BlockTable bt = trans.GetObject(doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;
                    BlockReference blockref = new BlockReference(position, id);
                    blockref.ScaleFactors = new Scale3d(1.0);
                    BlockTableRecord tbr = trans.GetObject(destDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                    editId = tbr.AppendEntity(blockref);
                    trans.AddNewlyCreatedDBObject(blockref, true);
                    trans.Commit();
                    tbr.Dispose();
                    bt.Dispose();
                }

                docLock.Dispose();
                destDb.Dispose();
                db.Dispose();
            }
            catch (System.Exception ee)
            {
                return ObjectId.Null;
            }

            return editId;
        }

        private void btn_update_Click(object sender, EventArgs e)
        {

        }

        private void xu_duan_zi_Click(object sender, EventArgs e)
        {

        }


        private void btn_tukuang_Click(object sender, EventArgs e)
        {
            BorderSet border = new BorderSet();
            if (border.ShowDialog() == DialogResult.OK)
            {

                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                DocumentLock docLock = doc.LockDocument();
                Database db = doc.Database;
                Editor edit = doc.Editor;
                PromptPointResult pr = edit.GetPoint("请输入点");
                if (pr.Status != PromptStatus.OK)
                {
                    MessageBox.Show("输入无效");
                    return;
                }
                Point3d position = pr.Value;
                ObjectId id1 = CopyDWG(border.Tukuang, position);
                ObjectId id2 = CopyDWG(border.Label, position);

                using (Transaction trans = doc.TransactionManager.StartTransaction())
                {
                    BlockReference br1 = trans.GetObject(id1, OpenMode.ForRead) as BlockReference;
                    BlockReference br2 = trans.GetObject(id2, OpenMode.ForWrite) as BlockReference;

                    try
                    {
                        Extents3d ext1 = br1.GeometricExtents;
                        Extents3d ext2 = br2.GeometricExtents;
                        double x1 = Math.Max(ext1.MinPoint.X, ext1.MaxPoint.X);
                        double y1 = Math.Max(ext1.MinPoint.Y, ext1.MaxPoint.Y);
                        double x2 = Math.Max(ext2.MinPoint.X, ext2.MaxPoint.X);
                        double y2 = Math.Max(ext2.MinPoint.Y, ext2.MaxPoint.Y);
                        double y12 = Math.Min(ext1.MinPoint.Y, ext1.MaxPoint.Y);
                        double y22 = Math.Min(ext2.MinPoint.Y, ext2.MaxPoint.Y);
                        double dy = (y1 - y12) - (y2 - y22);
                        br2.Position = new Point3d(br2.Position.X + x1 - x2 - 20, br2.Position.Y + y1 - y2 - dy + 20, 0);

                        ObjectIdCollection ic = new ObjectIdCollection();
                        ic.Add(id1);
                        ic.Add(id2);

                        string groupname = DateTime.UtcNow.ToString();
                        groupname = groupname.Replace(":", "-");

                        DBDictionary group_dict = trans.GetObject(db.GroupDictionaryId, OpenMode.ForWrite) as DBDictionary;
                        Group g = new Group();
                        g.Append(ic);
                        group_dict.SetAt(groupname, g);
                        trans.AddNewlyCreatedDBObject(g, true);

                    }
                    catch (System.Exception ee)
                    {
                    }

                    trans.Commit();
                }

                docLock.Dispose();
            }

        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = dialog.FileName;

                Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
                DocumentLock docLock = doc.LockDocument();
                Database db = doc.Database;
                Editor edit = doc.Editor;
                PromptPointResult pr = edit.GetPoint("请输入点");
                if (pr.Status != PromptStatus.OK)
                {
                    MessageBox.Show("输入无效");
                    return;
                }
                Point3d position = pr.Value;
                ObjectId id1 = CopyDWG(fileName, position);

                using (Transaction trans = doc.TransactionManager.StartTransaction())
                {
                    BlockReference br1 = trans.GetObject(id1, OpenMode.ForRead) as BlockReference;

                    try
                    {

                        ObjectIdCollection ic = new ObjectIdCollection();
                        ic.Add(id1);

                        DBDictionary group_dict = trans.GetObject(db.GroupDictionaryId, OpenMode.ForWrite) as DBDictionary;
                        Group g = new Group();
                        g.Append(ic);
                        trans.AddNewlyCreatedDBObject(g, true);

                    }
                    catch (System.Exception ee)
                    {
                    }

                    trans.Commit();
                }

                docLock.Dispose();
            }

        }

        private void add_Click(object sender, EventArgs e)
        {

            TreeNode nodes = new TreeNode("增加目录");
            treeView2.Nodes.Add(nodes);
            treeView2.LabelEdit = true;
            nodes.BeginEdit();

            string schema = "dctss_project9";
            string name = "test";
            string desc = "test";
            string sql = " insert into " + schema + ".volume values(default,'" + name + "','" + desc + "')";

            DataAdapter adapter = new DataAdapter();
            adapter.InitConnection();
            adapter.ExecuteSql(sql);
            adapter.CloseConnection();
        }

        private void dwgwriteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream("c:\\1.dwg", FileMode.Open);
            byte[] data = new byte[fs.Length];
            fs.Read(data,0,(int)fs.Length);
            fs.Close();

            DataAdapter adapter = new DataAdapter();
            adapter.InitConnection();
            sbyte sb = 120;
            adapter.add_dwg("dctss_project9", 1, "test", "test", null, null,null, data);

            byte[] file = ((dwg_item)adapter.getItems("dctss_project9", item_type.dwg_item, new int[] { 1 })[0]).file;


            FileStream wfs = new FileStream("c:\\2.dwg", FileMode.CreateNew);
            wfs.Write(file,0,file.Length);
            wfs.Close();

            adapter.CloseConnection();

        }

    }
}

